const express=require('express')
const router=express.Router()
const userCtrl=require('../controller/user.js')
const {User}=require('../model')
const { body, validationResult } = require('express-validator');
const userValidate=require("../validator/user")
const auth=require('../middleware/auth')
//用户登录
router.post('/users/login',userValidate.login, userCtrl.login)
//用户注册
router.post('/users',userValidate.register,(req,res,next)=>{
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next()
},
async (req,res,next)=>{
    try {
    let user= new User(req.body.user)
     console.log(req.body.user)
    await user.save()
    user=user.toJSON()
    delete user.password
        res.send({
            data:user
        })
    } catch (err) {
         next(err)
    }
})

//获取当前登录用户
router.post('/user', auth ,async (req,res,next)=>{
    try {
        //处理请求发送响应
        res.send({
            msg:200,
            user:req.user
        })
    } catch (err) {
         next(err)
    }
})
//更新当前登录用户
router.put('/user', async (req,res,next)=>{
    try {
        //处理请求发送响应
        res.send('login')
    } catch (error) {
         next(error)
    }
})
module.exports=router